using System;
using System.Linq;
using CMS.api.Entity;
using CMS.api.Model;
using CMS.api.Repository;
using CMS.api.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace CMS.api.Controllers
{
    // [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        // 数据库的增删改
        private ICURDable<Users> _userRepository;
        private ICURDable<Administrator> _administratorRepository;

        // 用于保存token的配置信息
        private TokenParameter _tokenParameter;

        // 用于读取配置文件的信息
        private readonly IConfiguration _configuration;

        public UsersController(
            IConfiguration configuration,
            ICURDable<Users> userRepository,
            ICURDable<Administrator> AdministratorRepository
        )
        {
            _userRepository = userRepository;

            _administratorRepository = AdministratorRepository;

            _configuration = configuration;
            _tokenParameter =
                _configuration
                    .GetSection("TokenParameter")
                    .Get<TokenParameter>();
        }


        // 根据Id删除用户信息(伪删除)
        [HttpDelete("{id}")]
        public dynamic DeleteUser(int id)
        {
            // 根据id找到用户，进行伪删除
            var user = _userRepository.Table.Where(x => x.Id == id).FirstOrDefault();

            user.IsDeleted = true;

            var tmp = new
            {
                Code = 200,
                Data = user,
                Msg = string.Format("删除id为{0}的用户信息成功", id)
            };

            return JsonHelper.Serialize(tmp);
        }


        // 根据用户Id修改用户是否被禁用
        [HttpPut, Route("IsActived/{id}")]
        public dynamic changeUserIsAdmina(int id, bool IsActived)
        {

            var user = _userRepository.GetById(id);
            // 如果是禁用状态,那么就启用,否则反之
            if (user.IsActived == true)
            {
                user.IsActived = false;
                user.UpdatedTime = DateTime.Now;
                _userRepository.Update(user);
                var tmp = new
                {
                    Code = 200,
                    Data = user,
                    Msg = "用户已被禁用"
                };
                return JsonHelper.Serialize(tmp);
            }
            else
            {
                user.IsActived = true;
                user.UpdatedTime = DateTime.Now;
                _userRepository.Update(user);
                var tmp = new
                {
                    Code = 200,
                    Data = user,
                    Msg = "用户已被启用"
                };
                return JsonHelper.Serialize(tmp);
            }

        }



        // 获取所有用户信息 并根据前端需求进行分页      
        [HttpGet]
        public dynamic Get([FromQuery] Pager pager)
        {
            // 前端传来的当前页
            var pageIndex = pager.PageIndex;
            // 前端传来的每页条数
            var pageSize = pager.PageSize;
            // 查询实例
            var users = _userRepository.Table.Where(x => x.IsDeleted == false);
            // 统计记录条数
            var rowTotal = users.Count();
            // 配合前端进行分页
            // Skip选择同跳过几条记录。  Take选取多少条记录
            var u = users.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            return new
            {
                Code = 200,
                Data = new { Data = u, Pager = new { pageIndex, pageSize, rowTotal } },
                Msg = "查询成功!"
            };

        }


        // 根据用户Id修改用户是否为管理员
        [HttpPut, Route("IsAdmina/{id}")]
        public dynamic changeUserIsAdmina(int id, NewIsAdmin isAdmin)
        {
            var user = _userRepository.GetById(id);

            // 如果是管理员 那么设置为普通用户,并且在管理员表中删除该用户
            if (user.IsAdmina == true)
            {
                //设置为普通用户,更新时间
                user.IsAdmina = isAdmin.IsAdmina;
                user.UpdatedTime = DateTime.Now;

                // 查找该用户,禁用该用户的管理员权限
                var admin = _administratorRepository.Table.Where(x => x.UserId == id).FirstOrDefault();
                // 未找到说明不是管理员
                if (admin == null)
                {
                    var tmp = new
                    {
                        Code = 1004,
                        Data = "",
                        Msg = "该用户不是管理员"
                    };
                    return JsonHelper.Serialize(tmp);
                }
                else
                {
                    admin.IsActived = false;
                    admin.UpdatedTime = DateTime.Now;
                    var tmp = new
                    {
                        Code = 200,
                        Data = user,
                        Msg = "修改为普通用户"
                    };
                    return JsonHelper.Serialize(tmp);
                }


            }
            // 如果不是管理员 那么设置为管理员,并且在管理员表中添加该用户
            else
            {

                //先查找该用户是否有记录,如果有那么就启用该用户的管理员权限,否则就添加该用户到管理员表
                var a = _administratorRepository.Table.Where(x => x.UserId == id).FirstOrDefault();
                // 不为空说明他当过管理员
                if (a != null)
                {
                    // 设置管理员表该用户启用管理员权限,并更新时间
                    a.IsActived = true;
                    a.UpdatedTime = DateTime.Now;
                    // 设置用户为管理员,并更新时间
                    user.IsAdmina = isAdmin.IsAdmina;
                    user.UpdatedTime = DateTime.Now;
                    _userRepository.Update(user);
                    var tmp2 = new
                    {
                        Code = 200,
                        Data = user,
                        Msg = "修改为管理员"
                    };
                    return JsonHelper.Serialize(tmp2);
                }
                // 没有当过管理员,就添加到管理员表
                else
                {
                    // 设置用户为管理员,并更新时间
                    user.IsAdmina = isAdmin.IsAdmina;
                    user.UpdatedTime = DateTime.Now;
                    _userRepository.Update(user);

                    // 如果是普通用户,那么就把该用户添加到管理员表
                    var admin = new Administrator
                    {
                        UserId = id
                    };
                    _administratorRepository.Inster(admin);
                    var tmp = new
                    {
                        Code = 200,
                        Data = user,
                        Msg = "修改为管理员"
                    };
                    return JsonHelper.Serialize(tmp);
                }

            }

        }

        // 注册用户
        // [AllowAnonymous]
        [HttpPost]
        public dynamic RegisterUser(NewUser model)
        {
            var username = model.Username.Trim();
            var password = model.Password.Trim();
            var remarks = model.Remarks.Trim();

            // 查找用户是否存在
            var u = _userRepository.Table.Where(x => x.Username == username).FirstOrDefault();

            // 如果用户不为空说明存在，那么就返回用户已存在
            if (u != null)
            {
                var res = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "用户已存在"
                };
                return JsonHelper.Serialize(res);
            }
            // 否则用户不存在,那么进行判断用户名或密码是否为空
            else
            {

                // 如果用户名或密码为空,不能注册
                if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
                {
                    var res = new
                    {
                        Code = 1004,
                        Data = "",
                        Msg = "用户名或密码为空"
                    };
                    return JsonHelper.Serialize(res);
                }
                // 否则注册用户
                else
                {
                    var user = new Users
                    {
                        Username = username,
                        Password = password,
                        Remarks = remarks,
                        IsAdmina = false,
                    };

                    _userRepository.Inster(user);

                    var res = new
                    {
                        Code = 200,
                        Data = user,
                        Msg = "注册成功"
                    };
                    return JsonHelper.Serialize(res);
                }

            }
        }

        //登录验证并签发Token
        // [AllowAnonymous]
        [HttpPost, Route("GetToken")]
        public dynamic GetToken(NewUser model)

        {
            //用户名
            var username = model.Username.Trim();
            // 用户密码
            var password = model.Password.Trim();

            var user = _userRepository.Table.Where(x => x.Username == username && x.Password == password).FirstOrDefault();

            // 判断是否找到用户
            if (user == null)
            {
                var tmp = new { Code = 1004, Data = "", Msg = "用户不存在=_=" };
                return JsonHelper.Serialize(tmp);
            }
            else
            {
                // 如果找到该用户,那么进行判断他是否被删除,没有删除那么登录登录成功,并签发token
                if (user.IsDeleted == true)
                {
                    var tmp2 =
                        new { Code = 1004, Data = "", Msg = "用户不存在=_=" };
                    return JsonHelper.Serialize(tmp2);
                }
                else
                {
                    var token =
                        TokenHelper.GenerateToken(_tokenParameter, user);
                    var refreshToken = "123456";
                    var tmp3 =
                        new
                        {
                            Code = 200,
                            Data =
                                new
                                {
                                    Data = user,
                                    Token = token,
                                    RefreshToken = refreshToken
                                },
                            Msg = "登录成功^_^"
                        };
                    return JsonHelper.Serialize(tmp3);
                }
            }
        }


        // 根据id获取用户信息
        [HttpGet("{id}")]
        public dynamic GetUserById(int id)
        {
            var user = _userRepository.GetById(id);
            return new
            {
                Code = 200,
                Data = user,
                Msg = "查询成功"
            };
        }


        // 根据用户名模糊查找用户信息
        [HttpPost, Route("FindeUser")]
        public dynamic FindUsersByUsername(NewUser user)
        {
            var username = user.Username;

            if (string.IsNullOrEmpty(username))
            {
                var tmp = new
                {
                    Code = 1004,
                    Data = new string[0],
                    Msg = "查找成功"
                };
                return JsonHelper.Serialize(tmp);
            }
            else
            {

                var users = _userRepository.Table.Where(x => x.Username.Contains(username)).ToList();

                var tmp = new
                {
                    Code = 200,
                    Data = users,
                    Msg = "查找成功"
                };

                return JsonHelper.Serialize(tmp);
            }

        }

        //根据Id修改指定用户信息
        [HttpPut("{id}")]
        public dynamic UpDateUser(NewUser model, int id)
        {

            var username = model.Username.Trim();
            var password = model.Password.Trim();
            var remarks = model.Remarks.Trim();
            var isadmain = model.IsAdmain;

            var user = _userRepository.GetById(id);
            user.Username = username;
            user.Password = password;
            user.Remarks = remarks;
            user.UpdatedTime = DateTime.Now;
            
            _userRepository.Update(user);

            var tmp = new
            {
                Code = 200,
                Data = user,
                Msg = "修改成功"
            };

            return JsonHelper.Serialize(tmp);

        }


    }
}
